//
//  LCOffLineViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/5.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh
import ObjectMapper
class LCOffLineViewController: UIViewController {
    var selectedProject : LCProjectListModel?
    lazy var itemArray : [MWCurrentLocationModel] = [MWCurrentLocationModel]()
    var offlineCount:((Int) -> Void)? = nil
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptylayout: UIView!
    @IBOutlet weak var emptylabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
       self.tableView.delegate = self
        self.tableView.dataSource = self
//        self.tableView.separatorInset = UIEdgeInsetsMake(5, 0, 0, 0)
//       // self.tableView.separatorInset = UIEdgeInsets.zero
//        self.tableView.separatorStyle = .singleLine
//        self.tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.separatorStyle = .singleLine
        self.view.backgroundColor = UIColor.init(red: 0.91, green: 0.91, blue: 0.91, alpha: 1);
        self.tableView.register(UINib.init(nibName: "LCSignCell", bundle: nil), forCellReuseIdentifier: "offline")
        
        var tableHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshDate))
        tableHeader?.stateLabel.isHidden = true
        self.tableView.mj_header = tableHeader
        
        self.addNotificationObserve()
    }
    private func addNotificationObserve(){
        let noficationName = Notification.Name.init(LCMainProjectNotification)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getMWLocationData(notification:)), name: noficationName, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notificRequest), name: NSNotification.Name(rawValue: XCRefreshNotification), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notificRequest), name: NSNotification.Name(rawValue: MDCQListNotification), object: nil)
        
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func refreshDate(){
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: MGQDListNotification), object: nil)
        self.setupMWLocationData()
    }
    
    @objc func notificRequest(){
        self.setupMWLocationData()
    }
    
    @objc func getMWLocationData(notification:Notification) {
        let userInfo = notification.userInfo as! [String:AnyObject]
        self.selectedProject = userInfo["project"] as? LCProjectListModel
        self.setupMWLocationData()
    }
    func setupMWLocationData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let projectid = ProjectId else{
            return
        }
        LCAPiMainManager.request(.GetMWLotion(start: "0", limit: "1000", sql: "SignedResult < 0 ", sqlParam: "{}", supplybaseid: projectid, AccountId: accountId)) { (result) in
            self.tableView.mj_header.endRefreshing()
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                if let resultDic = jsonString["Result"] as? [String: AnyObject] {
                    if let itemDic = resultDic["Items"] as? [[String: Any]] {
                        self.itemArray.removeAll()
                        self.itemArray.append(contentsOf: Mapper<MWCurrentLocationModel>().mapArray(JSONArray: itemDic))
                        self.offlineCount!(self.itemArray.count)
                        print(self.itemArray)
                        print(jsonString)
                        print(self.itemArray.first?.Location)
                        if self.itemArray.count == 0{
                            self.addEmptyDataView("暂无未签到数据")
                            return
                        }else{
                            self.removeEmptyView()
                        }
                    }
                }
                if self.itemArray.count > 0{
                    self.tableView.reloadData()
                }
                
                return
            }else{
                //WWProgressHUD.error("数据请求失败")
            }
        }
    }
    
    
}
extension LCOffLineViewController : UITableViewDataSource,UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 3 
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.00001
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 5))
        return headerView
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.itemArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : LCSignCell = tableView.dequeueReusableCell(withIdentifier: "offline") as! LCSignCell
        
        //cell.workerType.text = ((self.itemArray[indexPath.row].MigrantWorker!["MigrantWorkType"] as! Dictionary<String,Any>)["WorkType"] as! String) ?? ""
        print(cell)
        if self.itemArray[indexPath.row] != nil{
            cell.setupDataWith(model: self.itemArray[indexPath.row],flag: false)
        }
        cell.checkButton.isHidden = true
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let track = LCCheckTrackViewController(nibName: "LCCheckTrackViewController", bundle: nil)
//        track.currentProject = selectedProject
//        track.personInformation = self.itemArray[indexPath.row]
//        self.navigationController?.pushViewController(track, animated: true)
        let model:MWCurrentLocationModel = self.itemArray[indexPath.row]
        print("\(model.Location)")
        let mwDetail = MWDetailInfoViewController(nibName: "MWDetailInfoViewController", bundle: nil)
        mwDetail.reFreshData = {(value) in
            if value == true {
              self.setupMWLocationData()
            }
        }
        mwDetail.DemandBaseMigrantWorkerID = model.ID
        mwDetail.currentProjectName = selectedProject?.ProjectName
        mwDetail.currentProjectId = selectedProject?.MarketSupplyBaseID
        mwDetail.isZG = true
        mwDetail.LocateTime = model.Location?.object(forKey: "LocateTime") as? String
        //mwDetail.currentProject = selectedProject
        self.navigationController?.pushViewController(mwDetail, animated: true)
    }
}

extension LCOffLineViewController{
    func addEmptyDataView(_ status:String = "暂无数据"){
        self.tableView.isHidden = true
        self.emptylayout.isHidden = false
        self.emptylabel.text = status
    }
    func removeEmptyView(){
        self.tableView.isHidden = false
        self.emptylayout.isHidden = true
    }
}
